<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更新用户资料</span>
    </div>
    <!-- 内容区放表单 -->
    <el-form ref="form" label-width="80px" :model="userInfo" :rules="abc">
      <!-- 表单中的每一行，叫做 el-form-item -->
      <el-form-item label="登录账号">
        <el-input v-model="userInfo.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="userInfo.nickname"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="userInfo.email"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updateUser">确认修改</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { updateUserAPI } from '@/api/user'

export default {
  data() {
    return {
      // userInfo: {
      //   username: this.$store.state.user.user.username,
      //   // username: this.$store.state.模块名.数据名,
      //   nickname: this.$store.state.user.user.nickname,
      //   email: this.$store.state.user.user.email
      // }
      userInfo: { ...this.$store.state.user.user },
      // 验证规则
      abc: {
        nickname: [
          { required: true, message: '昵称必填', trigger: 'blur' },
          { min: 1, max: 10, message: '昵称长度2~10位', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱必填', trigger: 'blur' },
          { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    updateUser() {
      // 完整的验证，验证通过，则调用API方法
      this.$refs.form.validate(async valid => {
        if (!valid) return
        // console.log('验证通过，提交数据')
        const { data: res } = await updateUserAPI(this.userInfo)
        if (res.code === 0) {
          this.$message.success(res.message)
          // 更新成功，更新vuex中的 user 数据
          this.$store.dispatch('user/getUser')
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 重置表单方法
    resetForm() {
      // resetFields 恢复表单为最初的样子；去掉红色的表单验证提示
      this.$refs.form.resetFields()
      // 将vuex中的数据，更新到组件中
      this.userInfo = { ...this.$store.state.user.user }
    }
  }
}
</script>

<style lang="less" scoped>
.el-card {
  font-size: 13px;
}

.el-form {
  width: 500px;
}
</style>
